package com.example.booksdeal.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.booksdeal.BmobDBO.BooksDetail;
import com.example.booksdeal.R;
import com.example.booksdeal.basic.BooksDetailActivity;
import com.example.booksdeal.util.DBOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;

public class Book1Fragment extends Fragment {

    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private ListView listView;
    private String getName,getPrice,getTime,username,type,searchcontext;
    private String book_id;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bookfragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbOpenHelper = new DBOpenHelper(getActivity(),"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        Bundle bundle = getActivity().getIntent().getExtras();
        username = bundle.getString("username");
        type = bundle.getString("type");
        searchcontext = bundle.getString("searchcontext");
        listView = getActivity().findViewById(R.id.listView);
        final ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();

        String bql;//查询BookDetail表里所有数据
        BmobQuery<BooksDetail> query = new BmobQuery<>();
//        Cursor cursor;
        if (type == null && searchcontext == null) {
            bql =" select * from BooksDetail";//查询BookDetail表里所有数据
            query.setSQL(bql);
  //          cursor = db.query("BooksDetail",new String[]{"id","book_name","book_price","time"},
   //                 null,null,null,null,null);
        }else if (searchcontext == null){
            bql =" select * from BooksDetail where book_type = ?";
            query.setSQL(bql);
            query.setPreparedParams(new Object[]{type});
   //         cursor = db.query("BooksDetail",new String[]{"id","book_name","book_price","time"},
   //                 "book_type=?",new String[]{type},null,null,null);
        }else {
            bql =" select * from BooksDetail where book_type like ?";
            query.setSQL(bql);
            query.setPreparedParams(new Object[]{searchcontext});
            //        cursor = db.query("BooksDetail",new String[]{"id","book_name","book_price","time"},
    //                "book_name like ?", new String[]{"%" + searchcontext + "%"},null,null,null);
        }
        query.doSQLQuery(new SQLQueryListener<BooksDetail>(){

            @Override
            public void done(BmobQueryResult<BooksDetail> result, BmobException e) {
                if(e == null){
                    List<BooksDetail> object = (List<BooksDetail>) result.getResults();
                    if(object!=null && object.size()>0){
                        for (int i=0;i<object.size();i++){
                            HashMap<String,Object> map = new HashMap<String,Object>();
                            map.put("id",object.get(i).getBook_id());
                            map.put("name",object.get(i).getBook_name());
                            map.put("price",object.get(i).getBook_price());
                            map.put("time",object.get(i).getCreatedAt());
                            listItem.add(map);
                            SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),listItem,R.layout.activity_book_item,
                                    new String[]{"id","name","price","time"},new int[]{R.id.gid,R.id.bname,R.id.price,R.id.time});
                            listView.setAdapter(simpleAdapter);
                            Log.i("Test", "listItem: " + listItem);
                            //添加每个item点击事件处理
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(getActivity(), BooksDetailActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个activity
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", listItem.get(i).get("id").toString());
                                    bundle.putString("username",username);
                                    Log.i("Test", "onItemClick: " + listItem.get(i).get("id").toString());
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            });
                        }
                    }else{
                        Log.i("smile", "查询成功，无数据返回");
                    }
                }else{
                    Log.i("smile", "错误码："+e.getErrorCode()+"，错误描述："+e.getMessage());
                }
            }
        });

//        if (cursor != null && cursor.getCount() > 0){
//            while (cursor.moveToNext()){
//                book_id = cursor.getInt(cursor.getColumnIndex("id"));
//                getName = cursor.getString(cursor.getColumnIndex("book_name"));
//                getPrice = cursor.getString(cursor.getColumnIndex("book_price"));
//                getTime = cursor.getString(cursor.getColumnIndex("time"));

       //     }
    //    }
  //      cursor.close();
  //      db.close();
    }
}
